<template>
  <!-- #ifdef MP-WEIXIN -->
  <view class="login-container">
    <button 
      class="avatar-btn" 
      open-type="chooseAvatar" 
      @chooseavatar="onChooseAvatar"
    >
      <image 
        :src="avatarUrl" 
        mode="aspectFill" 
        class="avatar-preview"
      ></image>
      <text class="avatar-text">点击设置头像</text>
    </button>
    
    <button 
      class="login-btn" 
      open-type="getPhoneNumber" 
      @getphonenumber="onGetPhoneNumber" 
      @click="WXLogin"
    >
      一键登录
    </button>
  </view>
  <!-- #endif -->
</template>

<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/userdata'
import { request } from '@/utils/request'

const API_BASE_URL = 'https://37ace603.r34.cpolar.top'
const userStore = useUserStore()
const loading = ref(false)
const code = ref('')
const avatarUrl = ref('https://img1.baidu.com/it/u=4142671647,1106015361&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800')

const emit = defineEmits(['loginSuccess'])

const WXLogin = async () => {
  loading.value = true
  console.log('[关键节点] 开始微信一键登录')
  
  try {
    const loginRes = await uni.login({
      provider: 'weixin'
    })
    
    if (!loginRes.code) {
      throw new Error('获取微信登录code失败')
    }
    
    code.value = loginRes.code
    console.log('[关键节点] 获取到微信登录code:', code.value)
  } catch (err) {
    console.error('[关键节点] 获取微信登录code失败:', err)
    loading.value = false
    uni.showToast({ 
      title: '登录失败，请重试', 
      icon: 'none' 
    })
  }
}

const onGetPhoneNumber = async (e) => {
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    uni.showToast({ title: '获取手机号失败', icon: 'none' })
    loading.value = false
    return
  }

  try {
    const { encryptedData, iv } = e.detail
    
    const res = await uni.request({
      url: `${API_BASE_URL}/account/wechat/login/`,
      method: 'POST',
      data: {
        code: code.value,
        encryptedData,
        iv,
        device_id: uni.getSystemInfoSync().deviceId
      },
      header: {
        'content-type': 'application/json'
      }
    })

    if (res.data && res.data.user_id) {
      console.log('[关键节点] 微信一键登录成功', {
        user_id: res.data.user_id,
        phone: res.data.phone,
        time: new Date().toISOString()
      })
      
      userStore.setUserInfo({
        id: res.data.user_id,
        phone: res.data.phone,
        access_token: res.data.access,
        refresh_token: res.data.refresh,
        avatar: res.data.avatar,
        username: res.data.nickname ,
        is_wechat_bound: true
      })
      
      uni.showToast({ title: '登录成功' })
      emit('loginSuccess')
    } else {
      throw new Error(res.data.message || '登录失败')
    }
  } catch (err) {
    console.error('[关键节点] 微信一键登录失败:', err)
    uni.showToast({ 
      title: err.message || '登录失败', 
      icon: 'none' 
    })
  } finally {
    loading.value = false
  }
}

// 处理选择头像
const onChooseAvatar = async (e) => {
  const { avatarUrl: newAvatarUrl } = e.detail 
  console.log('选择的头像地址:', newAvatarUrl)
  avatarUrl.value = newAvatarUrl
  
  // 可以在这里将头像上传到服务器
  try {
    const tempFilePath = newAvatarUrl
    const uploadRes = await uni.uploadFile({
      url: `${API_BASE_URL}/upload/avatar/`,
      filePath: tempFilePath,
      name: 'avatar',
      header: {
        'Authorization': `Bearer ${userStore.userData.access_token}`
      }
    })
    
    if (uploadRes.statusCode === 200) {
      const data = JSON.parse(uploadRes.data)
      // 更新store中的头像
      userStore.setUserInfo({
        ...userStore.userData,
        avatar: data.avatar_url
      })
      uni.showToast({
        title: '头像更新成功',
        icon: 'success'
      })
    }
  } catch (err) {
    console.error('上传头像失败:', err)
    uni.showToast({
      title: '头像上传失败',
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
}

.avatar-btn {
  background: none;
  border: none;
  padding: 0;
  margin: 0 0 30rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-btn::after {
  border: none;
}

.avatar-preview {
  width: 150rpx;
  height: 150rpx;
  border-radius: 50%;
  margin-bottom: 10rpx;
  border: 2px solid rgba(56, 182, 255, 0.3);
  box-shadow: 0 0 10px rgba(56, 182, 255, 0.2);
}

.avatar-text {
  font-size: 28rpx;
  color: #666;
  margin-top: 10rpx;
}

.login-btn {
  margin: 40rpx 30rpx 0;
  color: white;
  border: none;
  border-radius: 40rpx;
  padding: 24rpx 0;
  font-size: 32rpx;
  box-shadow: 0 0 10px rgba(56, 182, 255, 0.2);
  transition: all 0.3s ease;
  background-color: #0b405e;
}

.login-btn:active {
  transform: scale(0.96);
  box-shadow: 0 0 5px rgba(56, 182, 255, 0.3);
}
</style>
